import 'dart:async';

class Task {
  Task({required this.fun, required this.complete});

  Completer<dynamic> complete;
  Future<dynamic> Function() fun;
}

///异步任务顺序执行
class AsyncTaskUtils {
  List<Task> taskList = [];
  Task? currentTask;

  void clear(){
    taskList.clear();
  }

  void syncRun(Task task) {
    taskList.add(task);
    _runTask();
  }

  void _runTask() async {
    if (currentTask == null) {
      if (taskList.isNotEmpty) {
        currentTask = taskList.first;
        taskList.removeAt(0);
        try {
          final res = await currentTask?.fun.call();
          currentTask?.complete.complete(res);
        } catch (e) {
          currentTask?.complete.completeError(e);
        }
        currentTask = null;
        _runTask();
      }
    }
  }
}
